<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="200px">
        <div class="title-bar">
          <img class="logo" src="../assets/logo.png" alt="logo" />
          <div class="title">启航用户中心</div>
        </div>
      </a-col>
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
      <a-col flex="80px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-button type="primary" @click="loginUserStore.logout">
              {{ loginUserStore.loginUser.username ?? "无名" }}
            </a-button>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { h, ref } from "vue";
import { CrownOutlined, HomeOutlined } from "@ant-design/icons-vue";
import { MenuProps } from "ant-design-vue";
import { useRouter } from "vue-router";
import { currentUserStore } from "@/store/userLoginStore";

const loginUserStore = currentUserStore();

// 确保在适当的时机调用 useRouter
const router = useRouter();

// 点击菜单后路由跳转
const doMenuClick = ({ key }: { key: string }) => {
  if (router) {
    router.push({
      path: key,
    });
  }
};

//刷新后获取当前页面路径，并设置当前选中项
const current = ref<string[]>(["/"]);

// 确保 router 存在后再调用 afterEach
if (router) {
  router.afterEach((to) => {
    current.value = [to.path];
  });
}

const items = ref<MenuProps["items"]>([
  {
    key: "/",
    icon: () => h(HomeOutlined),
    label: "主页",
    title: "主页",
  },
  {
    key: "/user/login",
    label: "用户登录",
    title: "用户登录",
  },
  {
    key: "/user/register",
    label: "用户注册",
    title: "用户注册",
  },
  {
    key: "/admin/userManage",
    icon: () => h(CrownOutlined),
    label: "用户管理",
    title: "用户管理",
  },
  {
    key: "others",
    label: h(
      "a",
      { href: "https://gitee.com/twf-player", target: "_blank" },
      "许七 个人主页"
    ),
    title: "许七 个人主页",
  },
]);
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
